<template>
  <!-- 趋势对比  -  国家和地区 -->

  <div style="position: relative;">

    <div v-if="echartShow">
      <div class="item-box">
        <div class="lt flex">
          <el-select v-model="yXdataType" size="small" placeholder="请选择" style="width: 120px;margin-right: 40px;" @change="handleDataChange">
            <el-option v-for="item in echartsOptions" :key="item.val" :label="item.name" :value="item.val" />
          </el-select>
          <slot name="left" />
        </div>
        <div class="rt flex">
          <slot name="right" />
          <div class="handle-box flex" style="margin-left: 40px;">
            <i :class="echartType=='line'?'iconfont icon-zhexiantu active':'iconfont icon-zhexiantu'" @click="setEchartType('line')" />
            <i
              :class="echartType=='lineArea'?'iconfont icon-jurassic_broken-line active':'iconfont icon-jurassic_broken-line'"
              @click="setEchartType('lineArea')"
            />
            <i
              :class="echartType=='bar'?'iconfont icon-zhuzhuangtu active':'iconfont icon-zhuzhuangtu'"
              style="font-size: 18px;"
              @click="setEchartType('bar')"
            />

            <i class="iconfont iconfont icon-xiazai" @click="downloadImg" />
          </div>
        </div>
      </div>
      <div :id="idName" class="chart-table" :style="{height:height,width:'100%'}" />
    </div>
    <div v-else style="color: #909399;font-size: 14px;height: 236px;line-height: 236px;text-align: center;">暂无数据</div>

  </div>
</template>

<script>
import {
  echartsOptions
} from '@/settings.js'
import {
  colorList
} from '@/settings.js'

const grid = {
  top: '40px',
  left: '10px',
  right: '40px',
  bottom: '20px',
  containLabel: true
}

const yAxisItem = {
  type: 'value',
  min: 0,
  axisLine: {
    show: false
  },
  boundaryGap: false,
  axisTick: {
    show: false
  },
  nameTextStyle: {
    color: 'rgba(51, 64, 74, 0.8)',
    padding: [0, 5, 5, 0],
    fontSize: 12
  },
  axisLabel: {
    color: '#666',
    fontSize: 16
  }
}

import {
  mapGetters
} from 'vuex'
export default {
  props: {
    height: {
      default: '450px',
      type: String
    },
    idName: {
      default: function() {
        return 'selectEchart' + new Date().getTime()
      },
      type: String
    },
    valList: { // 多选下拉框选中的值
      default: () => {
        return []
      },
      type: Object
    },
    echartData: {
      default: () => {
        return {}
      },
      type: Object
    },
    adchannelType: {
      type: String,
      default: () => {
        return 'SEARCH'
      }
    }
  },

  computed: {
    ...mapGetters([
      'sidebar'
    ]),
    echartsOptions() {
      const _that = this
      const arr = echartsOptions.map(item => {
        if (item.val === 'avgCptAmount' && _that.adchannelType === 'DISPLAY') {
          return {
            name: 'CPM',
            val: 'avgCpmAmount',
            fix: '$'
          }
        } else {
          return item
        }
      })

      return arr
    },
    opened() {
      return this.sidebar.opened
    }
  },
  watch: {
    opened() {
      if (this.dateEchart) {
        const that = this
        this.$nextTick(() => {
          if (this.dateEchart && this.dateEchart.resize) {
            setTimeout(() => {
              that.dateEchart.resize()
            }, 200)
          }
        })
      }
    },

    echartData: {
      deep: true,
      handler: function() {
        const obj = Object.values(this.echartData)
        if (obj.length) {
          this.echartShow = true
          this.handleDataChange()
        } else {
          this.echartShow = false
        }
      }
    }
  },
  data() {
    return {
      yXdataType: 'localSpendAmount',
      echartBox: undefined,
      echartType: 'line',
      echartShow: true
    }
  },
  mounted() {
    const el = document.getElementById(this.idName)
    this.dateEchart = this.$echarts.init(el)
    window.addEventListener('resize', () => {
      if (this.dateEchart && this.dateEchart.resize) {
        this.dateEchart.resize()
      }
    })

    this.handleDataChange()
  },
  beforeDestroy() {
    window.removeEventListener('resize', () => {})
  },
  methods: {

    setEchartType(type) {
      this.echartType = type
      this.$nextTick(() => {
        this.handleDataChange()
      })
    },

    handleDataChange() {
      // 循环出来x轴的数据;
      const that = this
      const key = this.valList[0].key
      const xData = this.echartData[key].map(item => {
        return item.date
      })
      const xAxis = {
        type: 'category',
        data: xData,
        boundaryGap: this.echartType === 'bar',

        axisTick: {
          show: false
        },
        axisLine: {
          lineStyle: {
            color: '#E5E5E5;',
            width: 1 // 这里是为了突出显示加上的
          }
        }

      }

      const maxArr = []
      // 循环出seriesData的数据
      var seriesData = this.valList.map((item, index) => {
        const data = this.echartData[item.key].map(v => {
          const num = v[this.yXdataType] * 1
          maxArr.push(num.toFixed(2))
          return num.toFixed(2)
        })

        const obj = {
          name: item.name,
          data,
          type: this.echartType,
          barMaxWidth: 30,
          boundaryGap: false,
          splitLine: {
            'show': false
          },
          lineStyle: {
            color: colorList[index] || 'rgba(84, 138, 249, 1)'
          }, // 线条的样式
          itemStyle: {
            color: colorList[index] || 'rgba(84, 138, 249, 1)'
            // opacity: 0 // 为0不会绘制图形拐点消失

          }
        }

        if (this.echartType === 'line') {
          const obj1 = {
            ...obj,
            type: 'line',
            showSymbol: false,
            symbol: 'circle',
            symbolSize: 12,
            lineStyle: {
              normal: {
                width: 2,
                color: colorList[index] || 'rgba(84, 138, 249, 1)'
              }

            }, // 线条的样式
            itemStyle: {
              normal: {
                color: colorList[index] || 'rgba(84, 138, 249, 1)',
                borderColor: '#ffffff', // 拐点边框颜色
                borderWidth: 3 // 拐点边框大小
              }
              // opacity: 0 // 为0不会绘制图形拐点消失

            }

          }

          return obj1
        } else if (this.echartType === 'lineArea') {
          const obj1 = {
            ...obj,
            type: 'line',
            lineStyle: {
              width: 0
            },
            showSymbol: false,
            itemStyle: {
              color: colorList[index] || 'rgba(84, 138, 249, 1)'
              // opacity: 0 // 为0不会绘制图形拐点消失
            },
            areaStyle: {},
            emphasis: {
              focus: 'series'
            }
          }

          return obj1
        } else {
          return obj
        }
      })

      // 设置y轴的数据

      let label = '{value}'
      const index = this.echartsOptions.findIndex(v => {
        return v.val === this.yXdataType
      })

      var max = 100
      if (this.echartsOptions[index].fix && this.echartsOptions[index].fix === '%') {
        label = '{value}' + this.echartsOptions[index].fix
        max = 100
      } else {
        const unit = this.$store.state.user.unit
        var unitTxt = ''
        if (unit === 'USD') {
          unitTxt = '$'
        } else {
          unitTxt = '￥'
        }
        label = unitTxt + '{value}'
        max = Math.max(...maxArr)
        if (max !== 0) {
          const gutter = max.toFixed(0).toString()
          var length = undefined
          if (gutter.length < 3) {
            length = 10
          } else if (gutter.length === 3) {
            length = 100
          } else if (gutter.length === 4) {
            length = 1000
          } else {
            length = 10000
          }
          const end = Math.ceil(max / length) * length
          max = end
        } else {
          max = 100
        }
      }

      const yData = {
        ...yAxisItem,
        name: this.echartsOptions[index].name,
        splitNumber: 5,
        max,
        interval: max / 5,
        min: 0,
        splitLine: {
          lineStyle: {
            type: 'dashed'
          }
        },
        axisLabel: {
          formatter: label,
          color: ' rgba(172, 182, 194, 1)'
        }
      }

      // 循环出legend
      const legend = {
        show: false,
        data: undefined,
        selected: {}
      }
      legend.data = this.valList.map(item => {
        return item.name
      })
      this.valList.forEach(item => {
        legend.selected[item.name] = item.selected
      })

      const options = {
        grid,
        legend,
        graphic: {
          type: 'image',
          bottom: 76,
          right: 60,
          style: {
            image: require('@/assets/images/base/logo.png'),
            width: 410,
            height: 66

          }
        },
        xAxis,
        yAxis: yData,
        series: seriesData,

        tooltip: [{
          trigger: 'axis',
          triggerOn: 'mousemove|click',
          backgroundColor: 'rgba(250, 250, 250, .8)',
          shaowColor: 'rgba(0, 0, 0, .2)',
          textStyle: {
            color: '#666',
            fontSize: '14px'
          },
          formatter: function(params) {
            let str = `<p style="font-size: 12px;margin-bottom:12px"> ${params[0].axisValueLabel}</p>`
            params.forEach(item1 => {
              let fix
              let suffix
              var fixArr = ['花费', '总花费', 'CPT', 'CPA', 'CPM', 'localSpendAmount', 'avgCptAmount', 'avgCpaAmount']
              var suffixArr = ['点击率', '转化率', 'ttr', 'conversionRate']
              if (fixArr.indexOf(that.yXdataType) !== -1) {
                fix = that.$store.state.user.unit === 'USD' ? '$' : '￥'
              }
              if (suffixArr.indexOf(that.yXdataType) !== -1) {
                suffix = '%'
              }

              str +=
                  `
                  <div class="flex" style="width: auto;font-size: 12px;">
                    <p style="margin-right:12px">
                    <span style="margin-right: 4px;display: inline-block;border-radius: 50%;height: 10px;width: 10px;background-color: ${item1.color};"></span>
                    <span >${item1.seriesName}</span>
                    </p>
                    <p>
                      <span>${fix || ''}${item1.value}${suffix || ''}</span>
                    </p>
                  </div>
              `
            })

            return str
          },
          axiosPointer: {
            type: 'line',
            lineStyle: {
              type: 'solid',
              color: 'rgba(0, 0, 0, 0.1)'
            }

          }
        }]

      }

      // 设置盒子
      setTimeout(() => {
        this.dateEchart.resize()
        this.dateEchart.setOption(options, true)
      }, 20)
    },

    resizeWidth() {
      if (this.dateEchart) {
        this.dateEchart.resize()
      }
    },

    // 下载图表
    downloadImg() {
      const picInfo = this.dateEchart.getDataURL({
        type: 'png',
        pixelRatio: 1.5, // 放大两倍下载，之后压缩到同等大小展示。解决生成图片在移动端模糊问题
        backgroundColor: '#fff'
      })
      const elink = document.createElement('a')
      elink.download = '3YData图表'

      elink.style.display = 'none'
      elink.href = picInfo
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
    }

  }
}
</script>

<style lang="scss" scoped="true">
  @import '~@/styles/variables.scss';

  .chart-table {
    width: 100% !important;
    overflow: hidden;

  }

  .item-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 24px;
    padding-bottom: 24px;
  }

  .handle-box {
    justify-content: flex-end;

    i {
      font-size: 18px;
      color: rgba(0, 0, 0, 0.45);
      cursor: pointer;
      margin-right: 12px;

      &.active,
      &:hover {
        color: $mainColor1;
      }
    }
  }
</style>
